package com.xs.designpattern;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * 兽人王
 *
 * @author xs
 */
public class OrcKing {
    private List<RequestHandler> handlers;

    /**
     * 构造函数进行构建责任链
     */
    public OrcKing() {
        buildChain();
    }

    /**
     * 构建责任链
     */
    private void buildChain() {
        handlers = Arrays.asList(new OrcCommander(), new OrcOfficer(), new OrcSoldier());
    }

    /**
     * 通过责任链处理请求
     */
    public void makeRequest(Request req) {
        //根据进来的请求类型匹配对应的处理人员进行处理这个请求
        handlers.stream().sorted(Comparator.comparing(RequestHandler::getPriority))
            .filter(handler -> handler.canHandleRequest(req)).findFirst().ifPresent(handler -> handler.handle(req));
    }
}
